package cn.wolfcode.web.controller;

import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password){
          try {


            /*Employee employee = employeeService.login(username, password);
            //session.setAttribute(UserContext.USER_IN_SESSION, employee);
            UserContext.setCurrentUser(employee);
            boolean status = employeeService.get(employee.getId()).isStatus();
            employee.setStatus(status);
                //判断是否是超级管理员,不是就查询
                if (!employee.isAdmin()){
                    List<String> expressions = permissionService.selectById(employee.getId());
                    UserContext.setPermission(expressions);
                }*/
            //获取subject主体
        Subject subject = SecurityUtils.getSubject();
        subject.getSession();

        //方式一:在封装token之前就直接对密码进行加密,再传给shiro直接对比相同
        //Md5Hash md5Hash = new Md5Hash(password, username,2);
        //UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toString());



        //把前端传过来的参数封装为令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //使用shiro提供的api来登录
        subject.login(token);

        return new JsonResult();
          } catch(UnknownAccountException e) {
              e.printStackTrace();
              return new JsonResult(false,"用户名不存在");
          }catch (IncorrectCredentialsException e){
              e.printStackTrace();
              return new JsonResult(false, "密码错误");
          }catch (DisabledAccountException e) { e.printStackTrace();
              return new JsonResult(false, e.getMessage());
          }
    }

   /* //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login.html";
    }*/

}
